function GeofenceHelper(map) {

    this.Map = map;

    this.RefreshGeofence = function(id_table) {
        CreateListGeofence(id_table, 1);
    }

    this.RefreshGeofenceForTrack = function(id_table) {
        CreateListGeofenceforTrack(id_table, 1);
    }

    this.EditGeofence = function(id) {
        $('#txtUnitColor').css("background-color", "blue");

        $('#DivEditArea').modal({
            onShow: function(dialog) {
                var index = getIndexFromId(id);

                var elem = document.getElementById("NameAreaEdit");
                elem.value = listGeofence[index].GetName();
                var elem2 = document.getElementById("deksripsiAreaEdit");
                elem2.value = listGeofence[index].GetDeskripsi();
                var elem3 = document.getElementById("alamatAreaEdit");
                elem3.value = listGeofence[index].GetAddress();
                //var elem_group = document.getElementById("ctl00_ContentPlaceHolder1_groupDropDownListEdit");
                //elem_group.value =


                $('#ctl00_ContentPlaceHolder1_groupDropDownListEdit option')
                .filter(function() { return $.trim($(this).text()) == listGeofence[index].GetGroup(); })
                .attr('selected', true);


                $("#EditAreaButton").click(function() {
                    var areaName = document.getElementById("NameAreaEdit").value;
                    var deskripsi = document.getElementById("deksripsiAreaEdit").value;
                    var location = document.getElementById("alamatAreaEdit").value;
                    var id_geo_group = document.getElementById("ctl00_ContentPlaceHolder1_groupDropDownListEdit").value;


                    if (areaName.length > 0) {

                        $.modal.close();

                        $.ajax({
                            type: "POST",
                            url: "Geofence.aspx/EditGeofence",
                            data: "{'id':'" + id + "','name': '" + areaName + "', 'deskripsi':'" + deskripsi + "','location':'" + location + "','id_geo_group':'" + id_geo_group + "'}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function(response) {
                                CreateListGeofence("excelDataTable", 1);
                            },
                            failure: function(response) {
                                alert(response.d);
                            },
                            error: function(xhr, err) {
                                alert(err);
                            }
                        });


                    }
                    else {
                        alert('area name harus diisi');
                    }


                });

                $("#BatalEditButton").click(function() {
                    $.modal.close();
                });
            }
        });
    }

    this.CreateGeofence = function(listCoordinate) {


        $('#txtUnitColor').css("background-color", "blue");

        $('#DivCreateArea').modal({
            onShow: function(dialog) {
                $("#CreateAreaName").click(function() {
                    var areaName = document.getElementById("areaName").value;
                    var deskripsi = document.getElementById("deskripsiArea").value;
                    var location = document.getElementById("alamatArea").value;
                    var id_geo_group = document.getElementById("ctl00_ContentPlaceHolder1_groupDropDownList").value;



                    // alert(id_geo_group);
                    //var idGroup = document.getElementById("ctl00_ContentPlaceHolder1_groupDropDownList").value;
                    //alert("<%=groupDropDownList.ClientID%>");
                    //alert("<%=GroupCheckBoxList.ClientID%>");

                    if (areaName.length > 0) {


                        var kontenKoordinat = "";
                        for (i in listCoordinate) {
                            kontenKoordinat += listCoordinate[i] + ";";
                        }


                        $.modal.close();

                        $.ajax({
                            type: "POST",
                            url: "Geofence.aspx/CreateGeofence",
                            data: "{'name': '" + areaName + "', 'deskripsi':'" + deskripsi + "','koord':'" + kontenKoordinat + "','location':'" + location + "','id_geo_group':'" + id_geo_group + "'}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function(response) {
                                //alert('f2');
                                CreateListGeofence("excelDataTable", 1);
                            },
                            failure: function(response) {
                                alert(response.d);
                            },
                            error: function(xhr, err) {
                                alert(err);
                            }
                        });


                    }
                    else {
                        alert('area name harus diisi');
                    }


                });
            }
        });
    }

    function UpdateClickEvents() {
        if (listGeofence) {
            for (i in listGeofence) {
                listGeofence[i].SetClickedFunction();
            }
        }
    }

    function clearOverlays() {
        if (listGeofence) {
            for (i in listGeofence) {
                //this.listGeofence[i].Polygon.setMap(null);
                google.maps.event.clearInstanceListeners(listGeofence[i].Polygon);
            }
        }
    }

    // Deletes all markers in the array by removing references to them
    function deleteOverlays() {
        if (listGeofence) {
            for (i in listGeofence) {

                //google.maps.event.clearInstanceListeners(listGeofence[i].GetPolygon());
                listGeofence[i].RemoveMapLabel();
                listGeofence[i].RemovePolygon();
                listGeofence[i] = null;
            }
            listGeofence.length = 0;
            listGeofence = [];

        }
    }

    function CloseModal() {
        $.modal.close();
    }

    function addAllColumnHeaders(myList, id_table) {
        var columnSet = [];
        var headerTr$ = $('<tr/>');


        for (var i = 0; i < myList.length; i++) {

            var rowHash = myList[i];

            var sentinel = 0;
            for (var key in rowHash) {
                if ($.inArray(key, columnSet) == -1) {
                    columnSet.push(key);
                    // alert(key);
                    //untuk menampilkan nama dan deskripsi saja pada tabel
                    if ((sentinel > 0 && sentinel < 3) || sentinel == 5) {
                        if (key == "name")
                            key = "Area";
                        else
                            key = "Deskripsi";

                        headerTr$.append($('<th/>').html(key));
                    }
                }
                sentinel++;
            }
        }

        //menambahkan kolom opsi dan group                
        columnSet.push("Pilihan");
        headerTr$.append($('<th/>').html("Pilihan"));

        //$("#" + id_table).append(headerTr$);

        return columnSet;
    }

    this.SearchListGeofence = function(keyWord, id_table) {

        if (keyWord.length == 0) {
            CreateListGeofence(id_table, 0);
        }
        else {
            SearchAreaByKeyword(keyWord, id_table);
        }
    }

    this.DeleteGeofence = function(id) {

        var index = getIndexFromId(id);
        listGeofence[index].RemoveMapLabel();
        listGeofence[index].RemovePolygon();

        $.ajax({
            type: "POST",
            url: "Geofence.aspx/DeleteGeofence",
            data: "{'id': '" + id + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
                //            setTimeout(function() {}, 1000);
                CreateListGeofence("excelDataTable", 2);
            },
            failure: function(response) {
                alert(response.d);
            },
            error: function(xhr, err) {
                alert(err);
            }
        });
    }

    function SearchAreaByKeyword(keyWord, id_table) {
        //$("#" + id_table).empty(); bodyTable
        $("#bodyTable").empty();


        $.ajax({
            type: "POST",
            url: "Geofence.aspx/SearchGeofence",
            data: "{'keyWord': '" + keyWord + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {

                var myList = $.parseJSON(response.d);
                var columns = addAllColumnHeaders(myList, id_table);

                for (var i = 0; i < myList.length; i++) {
                    var id = myList[i][columns[0]];
                    var name = myList[i][columns[1]];
                    var deskripsi = myList[i][columns[2]];
                    var koordinatString = myList[i][columns[3]];


                    var row$ = $('<tr/>');
                    for (var colIndex = 1; colIndex < columns.length; colIndex++) {
                        var cellValue = myList[i][columns[colIndex]];

                        if (cellValue == null) { cellValue = ""; }

                        if (colIndex == 1) {
                            row$.append($('<td/>').html("<a href='#' onclick='return dataTableClicked(" + id + ")'>" + cellValue + "</a>"));
                        }
                        else if (colIndex == 2) {
                            row$.append($('<td/>').html(cellValue));
                        }
                        else if (colIndex == 3) {
                            row$.append($('<td/>').html("<img  style=\"cursor:pointer; height:20px\" onclick=\"editArea(" + id + ");\" alt=\"Edit Area\" src=\"../images/edit-icon.png\" /><img  style=\"cursor:pointer; height:20px\"  onclick=\"deleteArea(" + id + ");\" alt=\"Hapus Area\" src=\"../images/delete-icon.png\" />"));
                        }
                    }

                    $("#" + id_table).append(row$);
                }

            },
            failure: function(response) {
                alert(response.d);
            },
            error: function(response) {
                alert('error');
            }
        });
    }

    function CreateListGeofence(id_table, sentinel) {

        // sentinel = 1 berarti perlu melakukan refresh semua data geofence pada peta
        // sentinel = 2 berarti hanya melakukan refresh pada peta pada area

        if (sentinel == 1) {
            deleteOverlays();
        }
        $("#bodyTable").empty();
        if (oTable != undefined) {
            oTable.fnClearTable();
            oTable.fnDestroy();
        };

        $.ajax({
            type: "POST",
            url: "Geofence.aspx/GetGeofenceList",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {

                var myList = $.parseJSON(response.d);

                var columns = addAllColumnHeaders(myList, id_table);

                for (var i = 0; i < myList.length; i++) {

                    var id = myList[i][columns[0]];
                    var name = myList[i][columns[1]];
                    var deskripsi = myList[i][columns[2]];
                    var koordinatString = myList[i][columns[3]];
                    var address = myList[i][columns[5]];
                    var group = myList[i][columns[4]];
                    var color = myList[i][columns[6]];

                    var row$ = $("<tr style='height:20px;font-size:11px;line-height:15px' onclick='return dataTableClicked(" + id + ")'/>");
                    for (var colIndex = 1; colIndex < columns.length; colIndex++) {
                        var cellValue = myList[i][columns[colIndex]];

                        if (cellValue == null) { cellValue = ""; }

                        if (colIndex == 3) {
                            row$.append($('<td/>').html("<img  title=\"Edit Data\" style=\"cursor:pointer; height:15px\" onclick=\"editArea(" + id + ");\" alt=\"Edit Area\" src=\"../images/edit-icon.png\" /><img  title=\"Hapus Data\" style=\"cursor:pointer; height:15px\"  onclick=\"deleteArea(" + id + ");\" alt=\"Hapus Area\" src=\"../images/delete-icon.png\" />"));
                        } else if (colIndex == 1) {
                            row$.append($('<td/>').html(cellValue));
                        } else if (colIndex == 2) {
                            row$.append($('<td/>').html(group));
                        }
                    }

                    $("#" + id_table).append(row$);
                    if (sentinel == 1) {
                        updateViewGeofence(id, name, deskripsi, koordinatString, 1, address, group, color);
                    }
                }

                oTable = $("#" + id_table).dataTable({
                    "bLengthChange": false,
                    "oLanguage": {
                        "sSearch": 'Cari Data:',
                        "sZeroRecords": "Tidak ada data yang ditemukan.",
                        "sInfo": "_START_ - _END_ dari total _TOTAL_ baris",
                        "sInfoEmpty": "0 - 0 dari 0 baris",
                        "sInfoFiltered": "(di filter dari total _MAX_ baris)"
                    },
                    "iDisplayLength": 15
                });
                $("#" + id_table + "_previous").html('');
                $("#" + id_table + "_next").html('');
            },
            failure: function(response) {
                alert(response.d);
            }
        });
    }

    function CreateListGeofenceforTrack(id_table, sentinel) {

        // sentinel = 1 berarti perlu melakukan refresh semua data geofence pada peta
        // sentinel = 2 berarti hanya melakukan refresh pada peta pada area

        if (sentinel == 1) {
            deleteOverlays();
        }
        alert('7');
        $("#bodyTable").empty();
        if (oTableGeofence != undefined) {
            oTableGeofence.fnClearTable();
            oTableGeofence.fnDestroy();
        };
        alert('8');

        $.ajax({
            type: "POST",
            url: "pages/Geofence.aspx/GetGeofenceList",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function(response) {
                alert('9');
                var myList = $.parseJSON(response.d);

                var columns = addAllColumnHeaders(myList, id_table);

                for (var i = 0; i < myList.length; i++) {

                    var id = myList[i][columns[0]];
                    var name = myList[i][columns[1]];
                    var deskripsi = myList[i][columns[2]];
                    var koordinatString = myList[i][columns[3]];
                    var address = myList[i][columns[5]];
                    var group = myList[i][columns[4]];
                    var color = myList[i][columns[6]];

                    var row$ = $("<tr style='height:20px;font-size:11px;line-height:15px' onclick='return geofenceDataTableClick(this," + id + ")'/>");
                    for (var colIndex = 1; colIndex < columns.length; colIndex++) {
                        var cellValue = myList[i][columns[colIndex]];

                        if (cellValue == null) { cellValue = ""; }

                        if (colIndex == 1) {
                            row$.append($('<td id="geofence' + id + '"/>').html(cellValue));

                            row$.append($('<td id="moving' + id + '"/>').html('0'));
                            row$.append($('<td id="stop' + id + '"/>').html('0'));

                            row$.append($('<td id="nosignal' + id + '"/>').html('0'));
                            row$.append($('<td id="total' + id + '"/>').html('0'));

                            //row$.append($('<td/>').html("<a href='#' onclick='return geofenceDataTableClick(" + id + ")'>" + cellValue + "</a>"));
                        }
                    }

                    $("#" + id_table).append(row$);
                    if (sentinel == 1) {
                        updateViewGeofence(id, name, deskripsi, koordinatString, 2, address, group, color);
                    }
                }

                oTableGeofence = $("#" + id_table).dataTable({
                    "bLengthChange": false,
                    "iDisplayLength": 30,
                    "oLanguage": {
                        "sSearch": 'Cari Area:',
                        "sZeroRecords": "Tidak ada data yang ditemukan.",
                        "sInfo": "_START_ - _END_ dari total _TOTAL_",
                        "sInfoEmpty": "0 - 0 dari 0",
                        "sInfoFiltered": "(difilter dari total _MAX_ )"
                    },
                    "aoColumnDefs": [
                          { 'bSortable': false, 'aTargets': [1, 2, 3, 4] }
                       ],
                    "fnDrawCallback": function(oSettings) {
                        setStatusInGeofence();
                    }
                    
                    //                    ,
                    //                    "fnFooterCallback": function(nRow, aaData, iStart, iEnd, aiDisplay) {
                    //                        /*
                    //                        * Calculate the total market share for all browsers in this table (ie inc. outside
                    //                        * the pagination)
                    //                        */
                    //                        var iTotalMarket = 0;
                    //                        for (var i = 0; i < aaData.length; i++) {
                    //                            iTotalMarket += aaData[i][4] * 1;
                    //                        }

                    //                        /* Calculate the market share for browsers on this page */
                    //                        var iPageMarket = 0;
                    //                        for (var i = iStart; i < iEnd; i++) {
                    //                            iPageMarket += aaData[aiDisplay[i]][4];
                    //                        }

                    //                        /* Modify the footer row to match what we want */
                    //                        var nCells = nRow.getElementsByTagName('th');
                    //                        nCells[1].innerHTML = iPageMarket;
                    //                    }
                });

            },
            failure: function(response) {
                alert(response.d);
            }
        });
    }

    function updateViewGeofence(id, name, deskripsi, koordinatString, status, address, group, color) {
        var listKoordinatString = koordinatString.split(";");
        var listPoint = [];
        for (i in listKoordinatString) {
            if (i < listKoordinatString.length - 1) {
                var latlongParts = listKoordinatString[i].substring(1, listKoordinatString[i].length - 1).split(",");
                listPoint.push(new google.maps.LatLng(latlongParts[0], latlongParts[1]));
            }
        }

        var newArea = new google.maps.Polygon({
            paths: listPoint,
            strokeColor: color,
            strokeOpacity: 0.8,
            strokeWeight: 1,
            // fillColor: "#0099FF",
            fillColor: color,
            fillOpacity: 0.1
        });

        newArea.setMap(map);



        var newGeofence = new Geofence(id, name, deskripsi, koordinatString, newArea, address, group);
        if (status == 1) {
            newGeofence.SetClickedFunction();
        }
        newGeofence.SetLabel();
        listGeofence.push(newGeofence);
        //alert(listGeofence.length);

    }

    function UpdateListGeofence(myList) {
        for (var i = 0; i < myList.length; i++) {
            for (var colIndex = 0; colIndex < columns.length; colIndex++) {
                var cellValue = myList[i][columns[colIndex]];
            }
        }
    }

    function getIndexFromId(id) {

        if (listGeofence) {
            for (i in listGeofence) {
                if (listGeofence[i].GetId() == id) {
                    return i;
                }
            }
        }
    }

    this.DataTableClicked = function(id_geofence) {

        var index = getIndexFromId(id_geofence);
        listGeofence[index].ClickedEvent();
    }

    this.DataTableClickedforTrack = function(id_geofence) {

        var index = getIndexFromId(id_geofence);
        listGeofence[index].ClickedEventForTrack();
    }

}

function Geofence(id, name, deskripsi, koordinatInString, polygon, address, group) {
    var Id = id;
    var Name = name;
    var Deskripsi = deskripsi;
    var Address = address;
    var Koordinat = koordinatInString;
    var Group = group;
    var mapLabel;

    var Polygon = polygon;


    this.GetId = function() {
        return Id;
    }

    this.GetGroup = function() {
        return Group;
    }

    this.GetAddress = function() {
        return Address;
    }


    this.GetName = function() {
        return Name;
    }

    this.GetDeskripsi = function() {
        return Deskripsi;
    }

    this.GetKoordinat = function() {
        return Koordinat;
    }


    this.GetPolygon = function() {
        return Polygon;
    }

    this.RemovePolygon = function() {
        Polygon.setMap(null);
    }

    this.RemoveMapLabel = function() {
        hideDeskripsi();
        mapLabel.setMap(null);
    }

    this.SetLabel = function() {
        var myLatlng = getCenter();
        mapLabel = new MapLabel({
            text: Name,
            position: myLatlng,
            map: map,
            fontSize: 13,
            fontColor: 'ff0000',
            align: 'center'
        });
        mapLabel.set('position', myLatlng);

    }

    this.SetClickedFunction = function() {
        google.maps.event.addListener(Polygon, 'click', this.GeofenceClicked);
    }

    this.GeofenceClicked = function(event) {

        var vertices = this.getPath();
        map.panTo(event.latLng);

        var contentString = "<div style=\"text-align:left; font-size:8pt; color:black;\" id=\"some_id_here\">Area : &nbsp;<b>" + Name + "</b><br>";
        contentString += "Alamat : &nbsp;<b>" + Address + "</b><br>";
        contentString += "Keterangan : &nbsp;<b>" + Deskripsi + "</b></div>";

        showDeskripsi()
        // Replace our Info Window's content and position
        //        infowindow.setContent(contentString);
        //        infowindow.setPosition(event.latLng);

        //        infowindow.open(map);
    }

    this.ClickedEvent = function() {

        var vertices = Polygon.getPath();
        var bounds = new google.maps.LatLngBounds();
        var i;

        //Iterate over the vertices. calculte centroid
        for (var j = 0; j < vertices.length; j++) {
            var xy = vertices.getAt(j);
            bounds.extend(xy);

        }

        var contentString = "<div style=\"text-align:left; font-size:8pt; color:black;\" id=\"some_id_here\">Nama Area : &nbsp;<b>" + Name + "</b><br>";
        contentString += "Keterangan : &nbsp;<b>" + Deskripsi + "</b></div>";
        showDeskripsi();


        map.panTo(bounds.getCenter());
        //        infowindow.setContent(contentString);
        //        infowindow.setPosition(bounds.getCenter());

        //        infowindow.open(map);
    }

    this.ClickedEventForTrack = function() {

        var vertices = Polygon.getPath();
        var bounds = new google.maps.LatLngBounds();
        var i;

        //Iterate over the vertices. calculte centroid
        for (var j = 0; j < vertices.length; j++) {
            var xy = vertices.getAt(j);
            bounds.extend(xy);

        }
        map.panTo(bounds.getCenter());
    }

    function showDeskripsi() {

        $("#deskripsi").show();

        $("#deskripsiVehicle").hide();
        $("#nameTextBox").val(Name);
        $("#deskripsiTextBox").val(Deskripsi);
        $("#alamatTextBox").val(Address);
        $("#grupTextBox").val(Group);

    }

    function hideDeskripsi() {
        $("#deskripsi").hide();
        $("#nameTextBox").val('');
        $("#deskripsiTextBox").val('');
        $("#alamatTextBox").val('');
        $("#grupTextBox").val('');
    }

    function getCenter() {
        var vertices = Polygon.getPath();
        var bounds = new google.maps.LatLngBounds();
        var i;

        //Iterate over the vertices. calculte centroid
        for (var j = 0; j < vertices.length; j++) {
            var xy = vertices.getAt(j);
            bounds.extend(xy);

        }


        return bounds.getCenter()

    }

}